﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Text.RegularExpressions;

using CypressDefense.Security.Shim;
using CypressDefense.Security.Shim.Configuration;
using CypressDefense.Security.Shim.Configuration.Caching;
using CypressDefense.Security.Shim.Configuration.Base;

namespace UnitTests
{
    [TestClass]
    public class ConfigurationTests
    {
        [TestMethod]
        public void LoadDefaultConfiguration()
        {
            ShimConfiguration config = ShimConfiguration.GetConfiguration();

            //DEFAULT CONFIGURATION
            //Make sure each section is enabled
            Assert.IsTrue(config.Enabled);
            Assert.IsTrue(config.Caching.Enabled);
            Assert.IsTrue(config.ContentSecurityPolicy.Enabled);
            Assert.IsTrue(config.StrictTransportSecurity.Enabled);
            Assert.IsTrue(config.XContentTypeOptions.Enabled);
            Assert.IsTrue(config.XFrameOptions.Enabled);
            Assert.IsTrue(config.XXssProtection.Enabled);

            //Test the caching defaults
            Assert.IsTrue(config.Caching.CacheControl.Enabled);
            Assert.AreEqual(config.Caching.CacheControl.Values.Count, 3);
            bool revalidate = false;
            bool noCache = false;
            bool noStore = false;
            foreach (AddElementCacheControl cacheControl in config.Caching.CacheControl.Values)
            {
                if (cacheControl.Value == CacheControlType.MustRevalidate)
                    revalidate = true;
                else if (cacheControl.Value == CacheControlType.NoCache)
                    noCache = true;
                else if (cacheControl.Value == CacheControlType.NoStore)
                    noStore = true;
            }
            Assert.IsTrue(revalidate);
            Assert.IsTrue(noCache);
            Assert.IsTrue(noStore);
            
            //Testing CSP defaults
            Assert.IsTrue(config.ContentSecurityPolicy.DefaultSource.Values.Count == 1);
        }

        [TestMethod]
        public void LoadCachingConfiguration()
        {
            ShimConfiguration config = ShimConfiguration.GetConfiguration();

            Assert.IsTrue(config.Caching.Enabled);
            Assert.IsTrue(config.Caching.CacheControl.Enabled);
            Assert.IsTrue(config.Caching.Expires.Enabled);
            Assert.IsTrue(config.Caching.Pragma.Enabled);

            foreach (LocationElement e in config.Caching.Exclude.Values)
            {
                Assert.IsNotNull(e.Path);
            }
        }

        [TestMethod]
        public void PathRegexTest()
        {
            Regex r = new Regex(@"^([-a-zA-Z0-9+&@#%=~_|!:,.;]+)(/[-a-zA-Z0-9+&@#%=~_|!:,.;]+)*$");
            Assert.IsTrue(r.IsMatch("default.aspx"));
        }
    }
}
